package com.pw.ba.base.controller;





import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pw.ba.base.pojo.Address;
import com.pw.ba.base.pojo.Order;
import com.pw.ba.base.service.GoodsOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/buy")
public class SettlementController {

    @Autowired
    GoodsOrderService goodsOrderService;


    @PostMapping("/goodsOrder")
    public void goodsOrder( @RequestBody Map map) throws ParseException {

        String orders = (String) map.get("orders");
        String address = (String) map.get("addre");
        String userId = (String) map.get("userId");
        int totalPrice = (int) map.get("totalPrice");
        //生成随机订单id
        String orderId = UUID.randomUUID().toString();

        //生成当前时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = df.format(new Date());
        java.util.Date creatDate = df.parse(format);
        System.out.println(creatDate);

        //转换order和address格式
        JSONArray orderArray =  JSONObject.parseArray(orders);
        JSONObject addressObject =  JSONObject.parseObject(address);
        ArrayList<Order> list = new ArrayList<>();

        String userName = addressObject.getString("userName");
        String telNumber = addressObject.getString("telNumber");
        String all = addressObject.getString("all");
        Address addre = new Address();
        addre.setOrderId(orderId);
        addre.setUserName(userName);
        addre.setTelNumber(telNumber);
        addre.setAll(all);

        for (int i = 0; i <orderArray.size() ; i++) {
            JSONObject jsonObject = (JSONObject) orderArray.get(i);
            Order order = new Order();
            order.setCreatDate(creatDate);
            order.setGoodId(jsonObject.getString("goodId"));
            order.setGoodName(jsonObject.getString("goodName"));
            String price = jsonObject.getString("goodPrice");
            int goodPrice = Integer.valueOf(price);
            String num = jsonObject.getString("num");
            int goodNum = Integer.valueOf(num);
            order.setGoodPrice(goodPrice);
            order.setGoodNum(goodNum);
            order.setOrderId(orderId);
            list.add(order);
        }


        goodsOrderService.creatOrderAddress(addre);
        goodsOrderService.creatOrder(list);
        goodsOrderService.creatUserOrder(userId,orderId,totalPrice);

        System.out.println("创建成功");




    }



}
